<template>
  <div id="froms">
    <div class="main-form">
      <div>{{ items["title"] }}</div>
      <div class="form-wra">
        <el-form-item
          v-for="(item, index) in renderFormItems"
          :key="item.prop"
          :label="item.label"
        >
          <el-input v-if="item.type === 'input'" :placeholder="item.placeholder"
            >佛挡杀佛</el-input
          >
        </el-form-item>
      </div>
    </div>
  </div>
</template>

<script>
// 创建canvas容器，用来计算字符串像素长度
const canvas = document.createElement("canvas");
const canvasContext = canvas.getContext("2d");
// 设置字体和大小
canvasContext.font = "13px arial";

// form-item的默认设置
const DEFAULT_ITEMS_OPTIONS = Object.freeze({
  width: "260px",
  maxlength: 20,
});

export default {
  name: "public-form",
  props: {
    items: Object,
    datum: Object,
    cascderThreeData: Array,
    loadData: Function,
    title: String,
  },
  data() {
    return {
      num: 1,
    };
  },
  watch: {},
  created() {},
  mounted() {},
  computed: {
    renderFormItems() {
      let result = [];
      const { searchParams } = this.items;
      if (Array.isArray(searchParams)) {
        result = searchParams.map((item) => {
          const options = { ...DEFAULT_ITEMS_OPTIONS };
          const { label = "", type, placeholder } = item;
          if (!placeholder) {
            const remindText = type === "input" ? "请输入" : "请选择";
            const [labelText = label] = /.*(?=[:：])/gi.exec(label) || [];
            options.placeholder = remindText + labelText;
            console.log("====", label);
          }
          const labelWidth =
            !label && type === "datetime" ? 0 : this.labelWidth;
          // return { ...options, labelWidth, ...item };
          return { ...options, ...item };
        });
      }
      console.log("---------", result);
      return result;
    },
    labelWidth() {
      let maxWidth = 0;

      const { searchParams } = this.items;

      if (Array.isArray(searchParams)) {
        maxWidth = searchParams.reduce((maxLen, item) => {
          const { label = "" } = item;
          const { width } = canvasContext.measureText(label);
          return width > maxLen ? width : maxLen;
        }, 0);
      }

      return maxWidth + 20;
    },
  },
  methods: {
    handleChange(value) {
      console.log(value);
    },
  },
};
</script>

<style  scoped>
.main-form {
  width: 400px;
}
</style>